package com.karaoke.android.kege

import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.support.annotation.UiThread
import com.facebook.common.executors.CallerThreadExecutor
import com.facebook.common.references.CloseableReference
import com.facebook.datasource.DataSource
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber
import com.facebook.imagepipeline.image.CloseableImage
import com.facebook.imagepipeline.request.ImageRequest
import rx.Observable

var inputType = InputType.PIN_YIN

enum class InputType
{
    PIN_YIN,
    SHOW_XIE,
    RI_WEN,
    HAN_WEN
}

fun Int.withAlpha(alpha: Int): Int
{
    require(alpha in 0..0xFF)
    return this and 0x00FFFFFF or (alpha shl 24)
}

fun Context.CacheBitmap(uri: Uri): Observable<Bitmap?>
{
    return Observable.unsafeCreate {
        val imageRequest = ImageRequest.fromUri(uri)
        val imagePipeline = Fresco.getImagePipeline()
        val dataSource = imagePipeline.fetchDecodedImage(imageRequest, this)

        dataSource.subscribe(object : BaseBitmapDataSubscriber()
                             {
                                 override fun onFailureImpl(dataSource: DataSource<CloseableReference<CloseableImage>>?)
                                 {
                                     it.onNext(null)
                                 }

                                 @UiThread
                                 override fun onNewResultImpl(bitmap: Bitmap?)
                                 {
                                     it.onNext(bitmap)
                                 }
                             }, CallerThreadExecutor.getInstance())
    }

}
